# 使用感知器模拟逻辑运算
import numpy as np

# 逻辑与
logic_and = [[0,0,0],
             [1,0,0],
             [0,1,0],
             [1,1,1]]
# 逻辑或
logic_or =[[0,0,0],
           [1,0,1],
           [0,1,1],
           [1,1,1]]
# 逻辑异或
logic_xor = [[0,0,0],
             [1,0,1],
             [0,1,1],
             [1,1,0]]

def percptron(logic):
    w = np.array([1,2]) #权重
    b = 0 #偏置
    a = 1 #步长
    for i in range(10):
        for j in range(4):
            x = np.array(logic[j][:2])
            # 感知器运算输出
            if (np.dot(w,x)+b)>0:
                y = 1
            else:
                y = 0
            # 实际值
            t = np.array(logic[j][2])
            # 计算w和b的梯度
            delta_w = -(t-y)*x
            delta_b = -(t-y)
            # 更新权重和偏置
            w = w - a*delta_w
            b = b - a*delta_b

            print("epoch {} logic {}：w=[{},{}] b={} y={} delta_w =[{},{}] delta_b={}".format(
                i,j,w[0],w[1],b,y,delta_w[0],delta_w[1],delta_b))


print("logic_and:")
percptron(logic_and)
print("logic_or:")
percptron(logic_or)
print("logic_xor:")
percptron(logic_xor)


